package com.kclm.xsap.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kclm.xsap.entity.*;
import com.kclm.xsap.service.*;
import com.kclm.xsap.utils.R;
import com.kclm.xsap.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/member")
public class MemberController {
    private static String IGNORE = "version";
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberBindRecordService memberBindRecordService;
    @Autowired
    private MemberCardService memberCardService;
    @Autowired
    private ReservationRecordService reservationRecordService;
    @Autowired
    private ScheduleRecordService scheduleRecordService;
    @Autowired
    private ClassRecordService classRecordService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private ConsumeRecordService consumeRecordService;
    @Autowired
    private CourseService courseService;

    /**
     * 跳转到会员列表页面
     */
    @GetMapping("/x_member_list.do")
    public String memberlist() {
        return "member/x_member_list";
    }

    /**
     * 获取会员列表数据
     */
    @PostMapping("/memberList.do")
    @ResponseBody
    public R memberVoList() {
        List<MemberEntity> memberEntities = memberService.list(null);
        List<MemberVo> memberVos = new ArrayList<>();
        for (MemberEntity memberEntity : memberEntities) {
            String[] cardName = memberBindRecordService.getCardName(memberEntity.getId());
            MemberVo memberVo = new MemberVo();
            memberVo.setId(memberEntity.getId())
                    .setMemberName(memberEntity.getName() + "(" + memberEntity.getPhone() + ")")
                    .setGender(memberEntity.getSex())
                    .setCardHold(cardName)
                    .setJoiningDate(memberEntity.getCreateTime())
                    .setNote(memberEntity.getNote());
            memberVos.add(memberVo);
        }
        return R.ok().put("data", memberVos);

    }

    /**
     * 会员添加操作
     */
    @GetMapping("/x_member_add.do")
    public String memberAddTO() {
        return "member/x_member_add";
    }
    @PostMapping("/memberAdd.do")
    @ResponseBody
    public R memberAdd(@Valid MemberEntity memberEntity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //说明验证没有通过，则把错误绑定前端的页面
            HashMap<String, String> errorMap = new HashMap<>();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return R.error(400, "非法参数").put("errorMap", errorMap);
        }
        if (memberService.save(memberEntity)) {
            return R.ok("添加成功").put("data", memberEntity);
        } else {
            return R.error("添加失败,请重试");
        }
    }

    /**
     * 会员修改操作
     */
    @PostMapping("/x_member_edit.do")
    @ResponseBody
    public R memberEditDo(Integer id) {
        MemberEntity MemberEntity = memberService.getById(id);
        return R.ok().put("data", MemberEntity);
    }
    @PostMapping("memberEdit.do")
    @ResponseBody
    public R memberEdit(MemberEntity memberEntity) {
        MemberEntity member = memberService.getById(memberEntity);
        BeanUtils.copyProperties(memberEntity, member, IGNORE);
        if (memberService.updateById(member)) {
            return R.ok("success");
        } else {
            return R.error("error");
        }
    }

    @GetMapping("x_member_list_details.do")
    public String memberListDetails(Integer id, Model model) {
        model.addAttribute("ID", id);
        return "member/x_member_list_details";
    }

    @PostMapping("/memberDetail.do")
    @ResponseBody
    public R memberDetail(Integer id) {
        MemberEntity memberEntity = memberService.getById(id);
        log.info("会员信息{}", memberEntity);
        return R.ok().put("data", memberEntity);
    }

    @PostMapping("/deleteOne.do")
    @ResponseBody
    public R deleteone(Integer id) {
        if (memberService.removeEntity(id)) {
            return R.ok();
        } else {
            return R.error("未知错误");
        }
    }

    /**
     * 会员卡信息
     */
    @PostMapping("cardInfo.do")
    @ResponseBody
    public R cardInfo(@RequestParam("id") Integer id) {
        QueryWrapper<MemberBindRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", id);
        List<MemberBindRecordEntity> memberBindRecordEntities = memberBindRecordService.selectList(wrapper);
        List<CardInfoVo> cardInfoVoList = new ArrayList<>();
        for (MemberBindRecordEntity memberBindRecordEntity : memberBindRecordEntities) {
            CardInfoVo cardInfoVo = new CardInfoVo();
            cardInfoVo.setBindId(memberBindRecordEntity.getId());
            cardInfoVo.setName(memberBindRecordService.getName(memberBindRecordEntity.getId()));
            cardInfoVo.setType(memberBindRecordService.getType(memberBindRecordEntity.getId()));
            cardInfoVo.setTotalCount(memberBindRecordEntity.getValidCount());
            LocalDateTime createTime = memberBindRecordEntity.getCreateTime();
            int addTime = memberBindRecordEntity.getValidDay();
            cardInfoVo.setDueTime(createTime.plusDays(addTime));
            cardInfoVo.setActiveStatus(memberBindRecordEntity.getActiveStatus());
            cardInfoVoList.add(cardInfoVo);
        }
        return R.ok().put("data", cardInfoVoList);
    }

    /**
     * 预约记录信息
     */
    @PostMapping("/reserveInfo.do")
    @ResponseBody
    public R reserveInfo(Integer id) {
        QueryWrapper<ReservationRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", id);
        List<ReservationRecordEntity> reservationRecordEntities = reservationRecordService.selectList(wrapper);
        System.out.println("reservationRecordEntities====>"+reservationRecordEntities);
        List<MemberDetailReservedVo> memberDetailReservedVos = new ArrayList<>();
        for (ReservationRecordEntity reservationRecordEntity : reservationRecordEntities) {
            ScheduleRecordEntity scheduleRecordServiceById = scheduleRecordService.getById(reservationRecordEntity.getScheduleId());
            System.out.println("scheduleRecordServiceById===>"+scheduleRecordServiceById);
            CourseEntity courseServiceById = courseService.getById(scheduleRecordServiceById.getCourseId());
            System.out.println("courseServiceById===>"+courseServiceById);

            System.out.println("member_id===>"+reservationRecordEntity.getMemberId());
            System.out.println("schedule_id===>"+reservationRecordEntity.getScheduleId());

            //根据member_id和schedule_id查询class_record表
            QueryWrapper<ClassRecordEntity> wrapperc = new QueryWrapper<>();
            wrapperc.eq("member_id", reservationRecordEntity.getMemberId());
            wrapperc.eq("schedule_id", reservationRecordEntity.getScheduleId());
            ClassRecordEntity classRecordEntity = classRecordService.getOne(wrapperc);
            System.out.println("classRecordEntityRC===>"+classRecordEntity.getReserveCheck());


            MemberDetailReservedVo memberDetailReservedVo = new MemberDetailReservedVo();
            memberDetailReservedVo.setCourseName(scheduleRecordService.getresName(reservationRecordEntity.getScheduleId()))
                    .setReserveTime(reservationRecordEntity.getCreateTime())
                    .setCardName(reservationRecordEntity.getCardName())
                    .setReserveNumbers(reservationRecordEntity.getReserveNums())
                    .setTimesCost(reservationRecordEntity.getReserveNums() * courseServiceById.getTimesCost())
                    .setOperateTime(reservationRecordEntity.getLastModifyTime())
                    .setOperator(reservationRecordEntity.getOperator())
                    .setReserveNote(reservationRecordEntity.getNote())
                    .setReserveStatus(classRecordEntity.getReserveCheck());
            memberDetailReservedVos.add(memberDetailReservedVo);
        }
        System.out.println("memberDetailReservedVos=========>"+memberDetailReservedVos);
        return R.ok().put("data", memberDetailReservedVos);
    }


    /**
     * 上课记录信息
     */
    @PostMapping("/classInfo.do")
    @ResponseBody
    public R classInfo(Integer id) {
        QueryWrapper<ClassRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", id);
        List<ClassRecordEntity> classRecordEntities = classRecordService.list(wrapper);
        List<ClassInfoVo> classInfoVoList = new ArrayList<>();
        for (ClassRecordEntity classRecordEntity : classRecordEntities) {
            ReservationRecordEntity reservationRecordEntity = reservationRecordService.getOne(new QueryWrapper<ReservationRecordEntity>()
                    .eq("member_id", classRecordEntity.getMemberId())
                    .eq("schedule_id", classRecordEntity.getScheduleId())
                    .eq("card_id", classRecordEntity.getBindCardId())
                    .eq("status", 1));
            ClassInfoVo classInfoVo = new ClassInfoVo();
            classInfoVo.setCourseName(scheduleRecordService.getresName(classRecordEntity.getScheduleId()));
            classInfoVo.setCheckStatus(classRecordEntity.getCheckStatus());
            classInfoVo.setCardName(classRecordEntity.getCardName());
            classInfoVo.setComment(classRecordEntity.getComment());
            // 获取上课记录课程开始时间
            QueryWrapper<ScheduleRecordEntity> wrappera = new QueryWrapper<>();
            wrappera.eq("id", classRecordEntity.getScheduleId());
            ScheduleRecordEntity scheduleRecordEntityOne = scheduleRecordService.getOne(wrappera);
            LocalDateTime classStartDateTime = LocalDateTime.of(scheduleRecordEntityOne.getStartDate(), scheduleRecordEntityOne.getClassTime());
            classInfoVo.setClassTime(classStartDateTime);
            //获取上课记录授课老师名称
            EmployeeEntity employeeById = employeeService.getById(scheduleRecordEntityOne.getTeacherId());
            if (employeeById != null) {
                classInfoVo.setTeacherName(employeeById.getName()) ;
            }
            //获取上课人数和使用次数
            QueryWrapper<ClassRecordEntity> wrapperc = new QueryWrapper<>();
            wrapperc.eq("schedule_id", classRecordEntity.getScheduleId());
            int countNum = classRecordService.count(wrapperc);
            classInfoVo.setClassNumbers(countNum);
            CourseEntity courseEntity = courseService.getById(scheduleRecordEntityOne.getCourseId());
            //int num=reservationRecordEntity.getReserveNums();
            //classInfoVo.setTimesCost(courseEntity.getTimesCost()*num);
            classInfoVo.setTimesCost(courseEntity.getTimesCost());
            classInfoVoList.add(classInfoVo);
        }
        return R.ok().put("data", classInfoVoList);
    }

    /**
     * 消费记录信息
     */
    @PostMapping("/consumeInfo.do")
    @ResponseBody
    public R consumeInfo(Integer id) {
        List<ConsumeInfoVo> consumeInfoVoList = new ArrayList<>();
        QueryWrapper<MemberBindRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", id);
        List<MemberBindRecordEntity> memberBindRecordEntities = memberBindRecordService.list(wrapper);
        for (MemberBindRecordEntity memberBindRecordEntity : memberBindRecordEntities) {
            QueryWrapper<ConsumeRecordEntity> wrappera = new QueryWrapper<>();
            wrappera.eq("member_bind_id", memberBindRecordEntity.getId());
            List<ConsumeRecordEntity> consumeRecordEntities = consumeRecordService.list(wrappera);
            for (ConsumeRecordEntity consumeRecordEntity : consumeRecordEntities) {
                ConsumeInfoVo consumeInfoVo = new ConsumeInfoVo();
                String cardName = consumeRecordService.getCardName(consumeRecordEntity.getMemberBindId());
                int validcount = consumeRecordService.getValid(consumeRecordEntity.getMemberBindId());
                consumeInfoVo.setCardName(cardName);
                consumeInfoVo.setTimesRemainder(validcount);
                consumeInfoVo.setNote(consumeRecordEntity.getNote());
                consumeInfoVo.setOperateTime(consumeRecordEntity.getCreateTime());
                consumeInfoVo.setCardCountChange(consumeRecordEntity.getCardCountChange());
                consumeInfoVo.setOperateType(consumeRecordEntity.getOperateType());
                consumeInfoVo.setMoneyCost(String.valueOf(consumeRecordEntity.getMoneyCost()));
                consumeInfoVo.setOperator(consumeRecordEntity.getOperator());
                consumeInfoVoList.add(consumeInfoVo);
            }
        }
        return R.ok().put("data", consumeInfoVoList);
    }

    /**
     * 会员搜索
     */
    @GetMapping("/toSearcherAll.do")
    @ResponseBody
    public R toSearcherAll() {
        List<MemberEntity> allMemberList = memberService.list(null);
        List<SearchMemberToBindVo> searchMemberToBindVos = new ArrayList<>();
        for (MemberEntity memberEntity : allMemberList) {
            SearchMemberToBindVo searchMemberToBindVo = new SearchMemberToBindVo();
            searchMemberToBindVo.setId(memberEntity.getId())
                    .setName(memberEntity.getName())
                    .setSex(memberEntity.getSex())
                    .setPhone(memberEntity.getPhone());
            searchMemberToBindVos.add(searchMemberToBindVo);
        }
        return R.ok().put("value", searchMemberToBindVos);
    }

    /**
     * 课程搜索
     */
    @GetMapping("toSearch.do")
    @ResponseBody
    public R toSearch() {
        List<MemberEntity> allMemberList = memberService.list(null);
        List<SearchMemberToBindVo> searchMemberToBindVos = new ArrayList<>();
        for (MemberEntity memberEntity : allMemberList) {
            SearchMemberToBindVo searchMemberToBindVo = new SearchMemberToBindVo();
            searchMemberToBindVo.setId(memberEntity.getId());
            searchMemberToBindVo.setName(memberEntity.getName());
            searchMemberToBindVo.setSex(memberEntity.getSex());
            searchMemberToBindVo.setPhone(memberEntity.getPhone());
            searchMemberToBindVos.add(searchMemberToBindVo);
        }
        return R.ok().put("value", searchMemberToBindVos);
    }


    @Value("src/main/resources/public/member_img/")
    private String uploadDir;

    /**
     * 修改会员头像
     */
    @PostMapping("/modifyMemberImg.do")
    @ResponseBody
    public R memberImg(@RequestParam("id") Integer id,
                       @RequestParam("avatarFile") MultipartFile file) {

        try {
            String newFileName = UUID.randomUUID().toString();
            //获取原来文件的扩展名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            newFileName = newFileName + suffix;

            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            Path filePath = uploadPath.resolve(newFileName);

            // 使用流的方式上传文件
            try (InputStream inputStream = file.getInputStream();
                 OutputStream outputStream = Files.newOutputStream(filePath)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            MemberEntity memberEntity = memberService.getById(id);

            //判断是否有头像，如果有，则先删除原来的头像
            String avatarUrl = memberEntity.getAvatarUrl();
            log.info("头像路径：{}", avatarUrl);




            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                Path oldFilePath = uploadPath.resolve(memberEntity.getAvatarUrl()); // 原来的头像路径
                log.info("原来的头像路径：{}", oldFilePath);
                try {
                    Files.delete(oldFilePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            memberEntity.setAvatarUrl(newFileName);
            if (memberService.updateById(memberEntity)) {
                return R.ok("上传头像成功！");
            } else {
                return R.error("上传图像失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("上传图像失败！");
    }
}
